package com.eagle.security.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.eagle.security.dao.UserLogDao;
import com.eagle.security.entries.UserLog;

@Repository
public class UserLogDaoImpl implements UserLogDao {

    @Resource
    private JdbcTemplate template;

    @Override
    public int saveUserLog(final UserLog mo) {
        KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        int res = getTemplate().update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                final String sql = "INSERT INTO user_log ( username  )  VALUES ( ? ) ";
                PreparedStatement ps = con.prepareStatement(sql, new String[] { "id" });
                ps.setString(1, mo.getUsername());
                return ps;
            }
        }, generatedKeyHolder);
        if (res > 0) {
            mo.setId(generatedKeyHolder.getKey().longValue());
        }
        return res;
    }

    @Override
    public int saveUserLogIncrease(UserLog mo) {
        final String sql = "INSERT INTO user_log ( username ) " + " VALUES ( ? ) ";
        return getTemplate().update(sql, mo.getUsername() );
    }

    @Override
    public int modifyUserLog(UserLog mo) {
        String sql = "UPDATE user_log SET username = ? WHERE id = ? ";
        return getTemplate().update(sql, mo.getUsername(), mo.getId() );
    }

    @Override
    public int deleteUserLogById(String id) {
        return getTemplate().update("DELETE FROM user_log  WHERE id = ?", id);
    }

    @Override
    public UserLog findUserLogById(String id) {
        String sql = "SELECT * FROM user_log  WHERE id = ?";
        List<UserLog> l = getTemplate().query(sql, userLogMapper, id);
        if (l.size() > 0) {
            return l.get(0);
        }
        return null;
    }

    private final RowMapper<UserLog> userLogMapper = new RowMapper<UserLog>() {
        @Override
        public UserLog mapRow(ResultSet rs, int arg1) throws SQLException {
            UserLog mo = new UserLog();
            mo.setId( rs.getLong("id") );
            mo.setUsername( rs.getString("username") );
            return mo;
        }
    };

    @Override
    public Map<String, Object> findUserLogMapById(String id) {
        String sql = "SELECT * FROM user_log  WHERE id = ?";
        List<Map<String, Object>> l = getTemplate().queryForList(sql, id);
        if (l.size() > 0) {
            return l.get(0);
        }
        return null;
    }

    @Override
    public List<UserLog> findUserLogsByCond(UserLog mo, int start, int pageSize) {
        StringBuffer sql = new StringBuffer("SELECT * FROM user_log  ");
        Object[] args = gernateUserLogWhereCond(sql, mo, start, pageSize);
        return getTemplate().query(sql.toString(), userLogMapper, args);
    }

    /**
     * 生成查询where条件 (包括where && MySQL)
     * 
     * @param b
     * @param mo
     * @param start
     * @param pageSize
     * @return
     */
    private Object[] gernateUserLogWhereCond(StringBuffer b, UserLog mo, int start, int pageSize) {
        List<Object> l = new ArrayList<Object>();
        b.append(" WHERE 1=1 ");
        if (mo != null) {
            if (!StringUtils.isBlank(mo.getUsername())) {
                b.append(" AND ").append(" username like ? ");
                l.add(mo.getUsername());
            }
        }
        b.append(" ORDER BY ").append(" id DESC ");
        if (start < 0 || pageSize < 0) {

        }
        else {
            b.append(" limit ?,?");
            l.add(start);
            l.add(pageSize);
        }
        return l.toArray(new Object[l.size()]);
    }

    @Override
    public List<Map<String, Object>> findUserLogMapsByCond(UserLog mo, int start, int pageSize) {
        StringBuffer sql = new StringBuffer("SELECT * FROM user_log  ");
        Object[] args = gernateUserLogWhereCond(sql, mo, start, pageSize);
        return getTemplate().queryForList(sql.toString(), args);
    }

    @Override
    public int findUserLogCountByCond(UserLog mo) {
        StringBuffer sql = new StringBuffer("SELECT count(1) FROM user_log  ");
        Object[] args = gernateUserLogWhereCond(sql, mo, -1, -1);
        return getTemplate().queryForInt(sql.toString(), args);
    }

    @Override
    public int checkExistWhenModifyUserLog(UserLog mo) {
        String sql = "select count(id) from user_log where name= ?";
        return getTemplate().queryForInt(sql, mo.getUsername());
    }

    @Override
    public int checkExistWhenSaveUserLog(UserLog mo) {
        String sql = "select count(id) from user_log where name= ? and id = ?";
        return getTemplate().queryForInt(sql, mo.getUsername(), mo.getId());
    }

    public JdbcTemplate getTemplate() {
        return template;
    }

    public void setTemplate(JdbcTemplate template) {
        this.template = template;
    }
}
